package com.flower.controller.common;
import com.flower.annotation.Log;
import com.flower.utils.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 通用请求处理
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 通用上传请求（单个）
     */
    @Log(name = "上传文件")
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            //以当前日期为文件名， 如2021/01/01/
            String objectName = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/";
            FileInfo fileInfo = fileStorageService.of(file)
                    .setPath(objectName) //保存到相对路径下，为了方便管理，不需要可以不写
                    .upload();  //将文件上传到对应地方
            // 返回结果
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileInfo.getUrl());
            ajax.put("fileName", fileInfo.getUrl());
            ajax.put("newFileName", getFileName(fileInfo.getUrl()));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.success(e.getMessage());
        }
    }

    /**
     * 获取文件名称 /profile/upload/2022/04/16/123.png -- 123.png
     *
     * @param fileName 路径名称
     * @return 没有文件路径的名称
     */
    public static String getFileName(String fileName) {
        if (fileName == null) {
            return null;
        }
        int lastUnixPos = fileName.lastIndexOf('/');
        int lastWindowsPos = fileName.lastIndexOf('\\');
        int index = Math.max(lastUnixPos, lastWindowsPos);
        return fileName.substring(index + 1);
    }
}
